package com.ye.study.utils;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.function.Consumer;

/**
 * @auther zzyy
 * @create 2024-04-02 17:18
 */
public class TaskDisposeUtils
{
    // 使用方式：TaskDisposeUtils.send(coupons,threadPool,TaskDisposeUtils::disposeTask);

    public static <T> void send(List<T> taskList, Executor threadPool,Consumer<? super T> consumer)
            throws InterruptedException
    {
        if (taskList == null || taskList.size() == 0)
        {
            return;
        }
        if(Objects.isNull(consumer))
        {
            return;
        }

        CountDownLatch countDownLatch = new CountDownLatch(taskList.size());
        for (T couponOrShortMsg : taskList)
        {
            threadPool.execute(() ->
            {
                try
                {
                    consumer.accept(couponOrShortMsg);
                } finally {
                    countDownLatch.countDown();
                }
            });
        }
        countDownLatch.await();
    }


    //============================================
    // 使用方式：TaskDisposeUtils.send(coupons,threadPool,TaskDisposeUtils::disposeTask);
    // lambda体,仅仅是调用方法methodA，没再做其它逻辑，即methodA正好是lambda体的实现逻辑
    //  即methodA                          正好是         lambda体的实现逻辑
    //  consumer.accept(couponOrShortMsg);                 sysout业务逻辑
    public static void disposeTask(String task)
    {
        System.out.println(String.format("【%s】disposeTask下发优惠卷或短信成功", task));
    }

    public static void disposeTaskV2(String task)
    {
        System.out.println(String.format("【%s】disposeTask下发邮件成功", task));
    }

    public static void disposeTaskV3(String task)
    {
        System.out.println(String.format("【%s】disposeTask下发注册码成功", task));
    }



    public static void disposeTaskV4(String task)
    {
        System.out.println(String.format("【%s】disposeTask下发XXXXXXX成功", task));
    }

}
